import { ElMessage } from 'element-plus';
import type { LocationQuery } from 'vue-router';
import { httpReqeustApi } from '/@/api/linxyun/base';
interface IConst {
	FlowID: string;
	ConstName: string;
	Value: string;
	Remarks: string;
}
interface IState {
	currentConst: Record<string, any>;
	isAddConst: boolean;
	constDialog: boolean;
	consts: IConst[];
}
/**
 * 常量相关函数
 * @param routeParams
 * @param keywords
 * @returns
 */
export default function (routeParams: LocationQuery, keywords: string[]) {
	const httpRequest = httpReqeustApi();
	const state = reactive<IState>({ consts: [], currentConst: {}, isAddConst: false, constDialog: false });
	// 查询常量定义
	const queryCountDefine = async () => {
		const queryRes = await httpRequest.Post('/crm/QueryFlowConst.action', {}, { FlowID: routeParams.FlowID });
		if (queryRes.code !== '0000' && !queryRes.success) {
			ElMessage({
				type: 'error',
				message: '查询常量失败',
				duration: BASE_API.MSG_SHOW_TIME,
			});
			console.log(queryRes.data);
			return;
		}
		const records = queryRes.Records || [];
		state.consts = records;
		// 将所有const 保存到关键字中
		records.forEach((item: IConst) => {
			keywords.push(item.ConstName);
		});
		console.log('queryCountDefine', queryRes);
	};

	const handleEditConst = (item: IConst) => {
		state.currentConst = item;
		state.isAddConst = false;
		state.constDialog = true;
		console.log(item);
	};
	const handleAddConst = () => {
		state.currentConst = {};
		state.isAddConst = true;
		state.constDialog = true;
	};
	// 提交常量定义
	const handleSubmitConst = async () => {
		if (state.isAddConst) {
			const res = await httpRequest.Post('/crm/add_dev_flow_const.action', {}, { ...state.currentConst, FlowID: routeParams.FlowID });
			if (res.code === '0000' && res.success) {
				ElMessage({
					type: 'success',
					message: '添加成功',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				console.log('addConst', res);
				queryCountDefine();
			} else {
				ElMessage({
					type: 'error',
					message: '添加失败',
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
			state.constDialog = false;
		} else {
			const res = await httpRequest.Post('/crm/update_dev_flow_const.action', {}, state.currentConst);
			if (res.code === '0000' && res.success) {
				ElMessage({
					type: 'success',
					message: '修改成功',
					duration: BASE_API.MSG_SHOW_TIME,
				});
				queryCountDefine();
				console.log('updateConst', res);
			} else {
				ElMessage({
					type: 'error',
					message: '修改失败',
					duration: BASE_API.MSG_SHOW_TIME,
				});
			}
			state.constDialog = false;
		}
		console.log('提交');
	};
	return {
		...toRefs(state),
		queryCountDefine,
		handleEditConst,
		handleAddConst,
		handleSubmitConst,
	};
}
